require "test/unit"
require "open3"

class TestTidyProject < Test::Unit::TestCase
  TEST_PROJECT_NAME = "TestProject"
  TEST_PROJECT_FILE_NAME = "test_project"
  AIR_CONFIG_FILE_PATH = "bin/#{TEST_PROJECT_FILE_NAME}.axml"
  def setup
   lib_path = File.expand_path('lib', __FILE__)
   $:.unshift(lib_path) unless $:.include?(lib_path)
  require 'tidy/compile'
  require 'tidy/air_packager'
    
    Dir.chdir "tmp" do
      puts `rm -fr #{TEST_PROJECT_NAME}`
      require '../lib/tidy_project'
      TidyProject.new(TEST_PROJECT_NAME)
    end
  end

	def test_demo
		in_project_folder do
		  	Tidy::Compile.demo(:main=>'src/app/views/MainView.as', 
				    :output=>TEST_PROJECT_FILE_NAME, 
		        :version=> "0.1",
		        :vars=>{:isTouch=>true,
		        	:variation=>0},
		        :do_not_launch=>true)
			config_file = File.new('src/DemoConfig.as','r')
	        assert file_contains_string?(config_file, 'isTouch : Boolean = true'), 'DemoConfig.as should add booleans'
	        assert file_contains_string?(config_file, 'variation : Number = 0'), 'DemoConfig.as should add numbers'
		end
	end
 
  def test_parse_options
  	#ENV['SPROUT_FLEX4SDK_TOOL'] = "/Users/christian/Library/Sprouts/cache/0.7/sprout-flex3sdk-tool-3.5.1"	
  	
  	args = {:main=>'src/app/views/MainView.as', 
              :output=>"multi_touch_window_02", 
              :version=> "0.1",
              :width=>640,
              :height=>480,
              :default_background_color=>"#FFFFFF",
              :paths=>["../multi-touch-lib/src", "../as3-lib/src"]}
    command = Tidy::Compile.parse_options(args);
    assert_nil(command =~ /width/, "custom parameters shouldn't be passed to the compiler")
    assert_not_nil(command =~/#FFFFFF/,"default parameters should be overriden");
    assert_not_nil(command =~/\/multi-touch-lib\/src/,"extra path should be added");
    assert_not_nil(command =~/\/as3-lib\/src/,"extra path should be added");
  end

  def test_air_main_template
  	in_project_folder do
  		template_path = 'config/templates/air.axml.erb';
  		assert File.exists?(template_path), "Main AIR template should be included in the project on creation"
  		#IO.popen('rake'){ |process| process.each { |line| puts line } }
  		do_silent_rake()
        assert File.exists?(AIR_CONFIG_FILE_PATH), "AXML config file should be auto-generated from root template"
        config_file = File.new(AIR_CONFIG_FILE_PATH,'r')
        assert_equal(
        	get_file_line_from_index(File.new(template_path,'r'), 1),
        	get_file_line_from_index(config_file, 1),
        	"AXML config file should be generated by main template")	
   	end
  end
  
  def test_air_custom_template
  	in_project_folder do
  		File.delete AIR_CONFIG_FILE_PATH if File.exists? AIR_CONFIG_FILE_PATH
  		template_path = "config/templates/#{TEST_PROJECT_FILE_NAME}.axml.erb"
        File.open(template_path, 'w') do |f|
          f << %{
           <?xml version="1.0" encoding="UTF-8"?> 
             <application xmlns="http://ns.adobe.com/air/application/1.0"> 
             <id><%=@app_name.gsub(\" \", \"\")%></id> 
             <version><%=@version.chomp%></version>
             <filename><%=@app_name%></filename>
             <initialWindow>
              <content><%=@content%></content>  
              <visible>true</visible>   
              <x>50</x><y>50</y>  
              <width><%=@width%></width>    
              <height><%=@height + 23%></height>
             </initialWindow>   
           </application> 
          }
        end
        do_silent_rake()
        assert File.exists?(AIR_CONFIG_FILE_PATH), "AXML config file should be auto-generated from custom template"
        config_file = File.new(AIR_CONFIG_FILE_PATH,'r')
        assert_equal(
        	get_file_line_from_index(File.new(template_path,'r'), 1),
        	get_file_line_from_index(config_file, 1),
        	"AXML config file should be generated by custom template")
  	end
  end

  def test_air_packaging
  	in_project_folder do
  		do_silent_rake()
  		Tidy::AirPackager.package(:id=>TEST_PROJECT_FILE_NAME, :do_not_launch=>true)
  		f = "config/air_cert.pfx";
  		assert File.exists?(f), "The certificate file should be created the first time the application is packaged"
  		content1 = File.read(f)
  		Tidy::AirPackager.package(:id=>TEST_PROJECT_FILE_NAME, :do_not_launch=>true)
  		content2 = File.read(f)
  		assert content1 == content2, "The certificate file shouldn't be recreated if already present"
  		f = "../releases/#{TEST_PROJECT_FILE_NAME}.air"
  		assert File.exists?(f), "The packaged file should be created in the releases folder"
  	end
  end
  
  def test_swf_creation
    in_project_folder do
      Tidy::Compile.swf(:main=>'src/app/views/MainView.as', :output=>TEST_PROJECT_FILE_NAME)
      Tidy::Generate.new(:template_id=>'web', :args=>[TEST_PROJECT_FILE_NAME])
      assert File.exists?("bin/#{TEST_PROJECT_FILE_NAME}.swf"), "Rake did not produce swf file"
    end
  end
  
  def do_silent_rake
  	Tidy::Compile.air(:main=>'src/app/views/MainView.as', 
		:output=>TEST_PROJECT_FILE_NAME, 
        :version=> "0.1",
        :do_not_launch=>true)
  end
  
  def get_file_line_from_index(file, index)
    
  	File.readlines(file.path)[index].to_s
  end

	def file_contains_string?(file, string)
		while (line = file.gets)
  			if line.include? string
  				return true
  			end
  		end
  		return false
	end

  #def test_add_libs
  #  in_project_folder do
  #    assert File.exists?('script'), "No script folder"
  #    assert File.exists?('rakefile.rb'), "No rakefile"
  #    assert_match "test_project", File.read('rakefile.rb')
  #    assert File.exists?('tasks'), "should be some tasks"
  #    assert File.exists?('bin'), "should be an empty bin folder"
  #  end
  #  
  #end
	#  def test_fcsh
	#    in_project_folder do
	#      Tidy::Compile.air(:main=>'src/app/views/MainView.as', 
	#                  :output=>TEST_PROJECT_FILE_NAME
	#                  #:do_not_launch=>true
	#                  )
	#      end
	#  end

# do packaging
# test content in package

  #def test_build
  #  
  #  in_project_folder do
  #    #puts `rake`
  #    Tidy::Compile.air(:main=>'src/app/views/MainView.as', 
  #                :output=>TEST_PROJECT_FILE_NAME
  #                #:do_not_launch=>true
  #                )
  #    assert File.exists?("bin/#{TEST_PROJECT_FILE_NAME}.swf"), "Rake did not produce swf file"
  #  end
  #end
  def test_rake
    
    in_project_folder do
      command = "rake --trace"
      stdin, stdout, stderr = Open3.popen3(command)
      stdout_text = stdout.read
      stderr_text = stdout.read
      puts "#{stdout_text}\n#{stderr_text}"
      assert_no_match /rake aborted/, stderr_text
      assert File.exists?("bin/#{TEST_PROJECT_FILE_NAME}.swf"), "Rake did not produce swf file"
    end
  end
  
  private
  def in_project_folder
    Dir.chdir "tmp/#{TEST_PROJECT_NAME}" do
      yield
    end
  end
end